package com.taojiazheng.serviceImpl.index;

import com.taojiazheng.dao.job.JobDao;
import com.taojiazheng.dao.job.JobEvaluatesDao;
import com.taojiazheng.entity.Jobinfo;
import com.taojiazheng.entity.Userinfo;
import com.taojiazheng.mapper.JobinfoMapper;
import com.taojiazheng.mapper.UserinfoMapper;
import com.taojiazheng.service.index.IndexService;
import com.taojiazheng.so.job.JobSo;
import com.taojiazheng.vo.job.JobEvaluatesVo;
import com.taojiazheng.vo.job.JobInfoVo;
import com.taojiazheng.vo.job.JobVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.management.counter.perf.PerfInstrumentation;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * @author 赵成林
 * @date 2017/11/23 19:53
 */
@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private JobDao jobDao;
    @Autowired
    private JobEvaluatesDao jobEvaluatesDao;
    @Autowired
    private UserinfoMapper userinfoMapper;

    /**
     * 首页job列表
     * 返回四个
     * 根据分类获取
     * @param
     * @return
     */
    public List<Jobinfo> getJobList(JobSo jobSo) {
        //return null;
        return jobDao.getJoBList(jobSo.getJobType());
    }

    /**
     * 获取岗位详情
     * 同时需要更新访问人数
     * @param jobSo
     * @return
     */
    public JobInfoVo getJobInfo(JobSo jobSo) {
        JobInfoVo jobInfoVo = jobDao.getJobInfo(jobSo.getJobId());
        List<JobEvaluatesVo> jobEvaluatesVos = jobEvaluatesDao.getList(jobSo.getJobId());
        jobInfoVo.setEvaluateList(jobEvaluatesVos);
        int userId = jobInfoVo.getUserId();
        Userinfo userinfo = userinfoMapper.getUserByUserId(userId);
        jobInfoVo.setUserName(userinfo.getRealName());
        float avgScore = this.getAvgScore(jobEvaluatesVos);
        jobInfoVo.setAvgScore(avgScore);
        //this.updateVisitNum(jobSo);
        return jobInfoVo;
    }
    /**
     * 更新浏览人数
     */
    public int updateVisitNum(JobSo jobSo) {
        //return 0;
        synchronized (this){
            JobInfoVo jobInfoVo = jobDao.getJobInfo(jobSo.getJobId());
            HashMap hashMap = new HashMap();
            hashMap.put("jobId",jobInfoVo.getJobId());
            hashMap.put("newNum",jobInfoVo.getVisitNum()+1);
            return jobDao.updateVisitNum(hashMap);
        }
    } 

    /**
     * 求评论的平均分
     * 保留两位小数
     */
    protected float getAvgScore(List<JobEvaluatesVo> jobEvaluatesVos){
        float sumScore = 0.0f;
        float avgScore = 0.0f;
        if(jobEvaluatesVos!=null && jobEvaluatesVos.size()>0){
            for(JobEvaluatesVo jobEvaluatesVo : jobEvaluatesVos){
                sumScore += jobEvaluatesVo.getScore();
            }
            avgScore = (float)(sumScore * 1.0 / jobEvaluatesVos.size());
            avgScore = new BigDecimal(avgScore+"").setScale(1,BigDecimal.ROUND_HALF_UP).floatValue();
        }

        return  avgScore;
    }
}
